<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\DemandBid;
use app\common\model\Favorites;
use app\common\model\Orders;
use think\Db;
use think\Exception;

class Demand extends Api
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';

    /**
     * @var $model \app\common\model\Demand
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Demand();
    }

    /**
     * 发布需求
     */
    public function publish()
    {
        $param = $this->request->param();
        $validate = new \app\api\validate\Demand();
        if (!$validate->check($param)){
            $this->error($validate->getError());
        }
        if (isset($param['id'])){
            if ($row = $this->model::get($param['id'])){
                if ($row->user_id != $this->auth->id){
                    $this->error('无权限');
                }
                unset($param['id']);
                $param['verify_status'] = 'await';
                $row->save($param);
                $this->success('修改成功');
            } else {
                $this->error('参数异常');
            }
        }
        $user = $this->auth->getUser();
        $user->demand()->save($param);
        $this->success('发布成功');
    }

    /**
     * 需求列表
     */
    public function lists()
    {
        [$where, $sort, $order, $offset, $limit] = $this->buildparams($this->model, '', '', '');
        $total = $this->model
            ->where($where)
            ->where('verify_status','=', 'allow')
            ->where('onshelf_status','=', '1')
            ->count();
        $list = $this->model
            ->where($where)
            ->where('verify_status','=', 'allow')
            ->where('onshelf_status','=', '1')
            ->with('user')
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        $result = array("total" => $total, "rows" => $list);
        $this->success('', $result);
    }

    /**
     * 需求详情
     */
    public function detail()
    {
        $id = input('param.id',0, 'intval');
        if (!$id){
            $this->error('参数错误');
        }
        if (!$row = $this->model->with('user.enterprise')->find($id)) {
            $this->error('未找到该需求');
        }
        if ($row->user_id != $this->auth->id && ($row->verify_status != 'allow' || $row->onshelf_status != 1)){
            $this->error('该需求无法展示');
        }
        $row->own_favorites = Favorites::where(['user_id'=> $this->auth->id,'collect_name'=>'demand','collect_id'=>$id])->find() ? 1 : 0;
        $row->bidders_count = DemandBid::where('demand_id','=', $id)->count();
        $this->success('', $row);

    }

    /**
     * 投标信息
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bidders()
    {
        $id = input('param.id',0, 'intval');
        $offset = input('param.offset',0, 'intval');
        $limit = input('param.limit',10, 'intval');
        if (!$id || !isset($offset) || !$limit || $offset < 0 || $limit <= 0){
            $this->error('参数错误');
        }
        if (!$row = $this->model->find($id)) {
            $this->error('未找到该需求');
        }
        if ($row->user_id != $this->auth->id){
            $this->error('没有权限');
        }
        $total = DemandBid::where('demand_id','=', $id)->count();
        $lists = (new DemandBid())->with('users.shop')->where('demand_id','=', $id)->order('create_time','desc')->limit($offset, $limit)->select();
        $this->success('',['total'=>$total,'rows'=>$lists]);
    }

    /**
     * 投标
     */
    public function bid()
    {
        $id = input('param.id',0, 'intval');
        if (!$id){
            $this->error('参数错误');
        }
        if (!$row = $this->model->find($id)) {
            $this->error('未找到该需求');
        }
        if ($row->user_id == $this->auth->id){
            $this->error('无法投标自己的需求');
        }
        if ($row->verify_status != 'allow' || $row->onshelf_status != 1){
            $this->error('该需求无法投标');
        }
        $data = [
            'user_id'=>$this->auth->id,
            'demand_id'=>$id
        ];
        if ($obj = DemandBid::where($data)->find()){
            $this->error('不可重复投标');
        }
        DemandBid::create($data);
        $this->success('投标成功');
    }

    /**
     * 选标
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function selectbid()
    {
        $id = input('param.id',0, 'intval');
        $user_id = input('param.user_id',0, 'intval');
        if (!$id || !$user_id){
            $this->error('参数错误');
        }
        if (!$row = $this->model->find($id)) {
            $this->error('未找到该需求');
        }
        if ($row->verify_status != 'allow' || $row->onshelf_status != 1){
            $this->error('该需求无法选标');
        }
        if (!$user = \app\common\model\User::get($user_id)){
            $this->error('该用户不存在');
        }
        $obj = DemandBid::where(['user_id'=>$user_id,'demand_id'=>$id,'status'=>0])->find();
        if (!$obj){
            $this->error('该用户未投标或已被选标');
        }
        $data = [
            'demand_id'  => $id,
            'aid'       => $this->auth->id,
            'bid'       => $user_id,
            'title'     => $row->title,
            'quantity'  => 1,
            'price'     => $row->budget,
            'amount'    => $row->budget,
            'verify_status'=> 'allow'
        ];
        Db::startTrans();
        try {
            Orders::create($data);
            $obj->status = 1;
            $obj->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('选标成功');
    }

    /**
     * 我的需求统计
     * @throws Exception
     */
    public function mycount()
    {
        $user = $this->auth->getUser();
        $demand['on'] = $user->demand()->where(['onshelf_status'=>'1'])->count();
        $demand['off'] = $user->demand()->where(['onshelf_status'=>'0'])->count();
        $this->success('',$demand);
    }

    /**
     * 我的需求列表
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function mylist()
    {
        [$where, $sort, $order, $offset, $limit] = $this->buildparams($this->model, '', '', '');
        $total = $this->model
            ->where($where)
            ->where('user_id','=', $this->auth->id)
            ->count();
        $list = $this->model
            ->where($where)
            ->where('user_id','=', $this->auth->id)
            ->with('user')
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
        if ($list){
            foreach ($list as $item){
                $item->hasBid = 0;
                if (DemandBid::where('demand_id','=',$item->id)->find()){
                    $item->hasBid = 1;
                }
            }
        }
        $result = array("total" => $total, "rows" => $list);
        $this->success('', $result);
    }

    /**
     * 上架需求
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function upsale()
    {
        $id = input('param.id',0, 'intval');
        if (!$id){
            $this->error('参数错误');
        }
        if (!$row = $this->model::get($id)) {
            $this->error('未找到该需求');
        }
        if ($row->user_id != $this->auth->id){
            $this->error('没有权限');
        }
        if ($row->onshelf_status == 1){
            $this->error('不要重复上架');
        }
        $row->onshelf_status = 1;
        $row->verify_status = 'await';
        $row->save();
        $this->success('上架成功，请等待审核');
    }

    /**
     * 下架需求
     * @throws \think\exception\DbException
     */
    public function downsale()
    {
        $id = input('param.id',0, 'intval');
        if (!$id){
            $this->error('参数错误');
        }
        if (!$row = $this->model::get($id)) {
            $this->error('未找到该需求');
        }
        if ($row->user_id != $this->auth->id){
            $this->error('没有权限');
        }
        if ($row->onshelf_status == 0){
            $this->error('不要重复下架');
        }
        $row->onshelf_status = 0;
        $row->save();
        $this->success('下架成功');
    }
}